﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.IO;
using RPGMapa.Data;
using System.Windows.Forms;

namespace RPGMapa
{
    static public class MapIO
    {
        public static string Encode(Map m)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(m.Name + '#');
            sb.Append(m.TileNumber.X.ToString() + '#');
            sb.Append(m.TileNumber.Y.ToString() + '#');
            sb.Append(m.TileSize.X.ToString() + '#');
            sb.Append(m.TileSize.Y.ToString() + '#');
            sb.Append("Image export was droped" + '#');
            sb.Append(m.Info.ToString() + '#');
            sb.Append("END_OF_FILE");

            return sb.ToString();
        }

        public static Map Decode(string file)
        {
            Map output = new Map();
            string[] items = file.Split('#');
            output.Name = items[0];
            output.TileNumber = new Vector2(
                int.Parse(items[1]),
                int.Parse(items[2]));
            output.TileSize = new Vector2(
                int.Parse(items[3]),
                int.Parse(items[4]));
            //output.Layer = DecodeBitmap(items[5], output.TileNumber.X * output.TileSize.X, output.TileNumber.Y * output.TileSize.Y);
            output.Info = DecodeStringMatrix(items[6], output.TileNumber.X, output.TileNumber.Y);
            return output;
        }

        private static StringMatrix DecodeStringMatrix(string str, int width, int height)
        {
            StringMatrix output = new StringMatrix(width, height);
            string[] values = str.Split('@');
            int contador = 0;

            for (int j = 0; j < height; j++)
            {
                for (int i = 0; i < width; i++)
                {
                    if (values[contador] == "0")
                    {
                        output[i, j] = "False";
                    }
                    else
                    {
                        output[i, j] = "True";
                    }
                    contador++;
                }
            }
            return output;
        }
    }
}
